﻿using Biz.Buffer;
using Biz.EF.Platform.SG;
using Hjt212Parser;
using log4net;
using System;
using System.Linq;

namespace Biz.Process
{
    public static class ProcessorAlarm
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ProcessorAlarm));
        public static void ProcessOverflow(string content)
        {
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes))
                {
                    return;
                }
                if (!datatime.HasValue)
                {
                    return;
                }
                var enterpriseName = CommonInformation.GetPollutionSourceNameByMn(mn);
                if (enterpriseName == null)
                {
                    return;
                }
                bool? isNationalControl = CommonInformation.IsNationalControl(mn);

                if (!isNationalControl.HasValue)
                {
                    return;
                }
                ProcessorHelper.RemoveMasterFactor(codes, true);

                using (var pCtx = new PlatformXpfContext())
                {
                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        double up;
                        double down;
                        int intervalHours;
                        if (isNationalControl.Value)
                        {
                            if (contam?.一级上限 == null || contam.一级下限 == null)
                            {
                                continue;
                            }
                            up = contam.一级上限.Value;
                            down = contam.一级下限.Value;
                            intervalHours = 24;
                        }
                        else
                        {
                            if (contam?.二级上限 == null || contam.二级下限 == null)
                            {
                                continue;
                            }
                            up = contam.二级上限.Value;
                            down = contam.二级下限.Value;
                            intervalHours = 24;
                        }

                        var begin = datatime.Value.AddHours(-intervalHours);

                        var rtd = Parser.GetDoubleByKey(code + "-Rtd", content);
                        if (!rtd.HasValue)
                        {
                            continue;
                        }

                        if (rtd.Value <= up && rtd.Value >= down)
                        {
                            continue;
                        }

                        var alarmType = CommonInformation.GetAlarmTypeByCode("overflow");
                        if (alarmType == null)
                        {
                            continue;
                        }
                        var record = pCtx.报警记录
                            .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                            .Where(t => t.企业排口ID == port.ID)
                            .Where(t => t.报警时间 >= begin && t.报警时间 <= datatime)
                            .Where(t => t.报警异常数据类型ID == alarmType.ID)
                            .FirstOrDefault(t=>t.内容.Contains("," +contam.名称+ "超标"));
                        if (record != null)
                        {
                            continue;
                        }
                        record = new 报警记录
                        {
                            企业基本信息ID = port.企业基本信息ID,
                            报警时间 = datatime,
                            内容 = enterpriseName + "(" + port.排放口名称 + "):" +
                                 datatime.Value.ToString("yyyy-MM-dd HH:mm:ss") + "," + contam.名称 + "超标，浓度为 " +
                                 rtd.Value + ",标准范围是：" + down + "--" + up + ".",
                            报警异常数据类型ID = alarmType.ID,
                            报警方式 = "Email",
                            发送结果标志ID = 401,
                            是否发送 = false,
                            报警方式ID = 201,
                            企业排口ID = port.ID,
                            发送结果 = "未发送",
                            次数 = 0,
                            管理者分级代码 = "false"
                        };
                        pCtx.报警记录.Add(record);
                    }
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
        }
        public static void ProcessToNewConcentration(string content)
        {
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes))
                {
                    return;
                }

                if (!datatime.HasValue)
                {
                    return;
                }
                var enterpriseName = CommonInformation.GetPollutionSourceNameByMn(mn);
                if (enterpriseName == null)
                {
                    return;
                }
                ProcessorHelper.RemoveMasterFactor(codes, true);
                using (var pCtx = new PlatformXpfContext())
                {
                    foreach (var code in codes)
                    {
                        var rtd = Parser.GetDoubleByKey(code + "-Rtd", content);
                        if (!rtd.HasValue)
                        {
                            continue;
                        }

                        var newRtdRecord = pCtx.最新浓度
                            .Where(t => t.mn.Equals(mn))
                            .Where(t => t.code.Equals(code)).OrderBy(t => t.id).FirstOrDefault();
                        if (newRtdRecord != null)
                        {
                            if (Math.Abs(newRtdRecord.rtd - rtd.Value) >= 0.001)
                            {
                                if (newRtdRecord.datatime < datatime.Value)
                                {
                                    newRtdRecord.datatime = datatime.Value;
                                }
                            }
                            //Log.Info("---->" +content);

                            //Log.Info("---->"+ newRtdRecord.rtd +"\t"+ rtd.Value +"\n"+ Math.Abs(newRtdRecord.rtd - rtd.Value)+"\t"+ (Math.Abs(newRtdRecord.rtd - rtd.Value) >= 0.001));
                        }
                        else
                        {
                            newRtdRecord = new 最新浓度
                            {
                                mn = mn,
                                code = code,
                                datatime = datatime.Value,
                                rtd = rtd.Value
                            };
                            pCtx.最新浓度.Add(newRtdRecord);
                        }
                        if (newRtdRecord.updatetime < datatime.Value)
                        {
                            newRtdRecord.updatetime = datatime.Value;
                        }

                        newRtdRecord.rtd = rtd.Value;
                    }
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
        }
        public static void ProcessConstant()
        {
            try
            {
                using (var pCtx = new PlatformXpfContext())
                {
                    var all = pCtx.最新浓度.ToList();
                    foreach (var item in all)
                    {
                        bool? isNationalControl = CommonInformation.IsNationalControl(item.mn);

                        if (!isNationalControl.HasValue)
                        {
                            return;
                        }

                        var port = CommonInformation.GetLetportByMn(item.mn);
                        if (port == null)
                        {
                            return;
                        }

                        var enterpriseName = CommonInformation.GetPollutionSourceNameByMn(item.mn);
                        if (string.IsNullOrWhiteSpace(enterpriseName))
                        {
                            return;
                        }

                        var intervalHours = isNationalControl.Value ? 2 : 4;
                        var alarmType = CommonInformation.GetAlarmTypeByCode("constant");
                        if (alarmType == null)
                        {
                            return;
                        }

                        if ((item.updatetime - item.datatime).TotalHours > intervalHours+1)
                        {
                            var record = pCtx.报警记录
                                .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                                .Where(t => t.企业排口ID != null && t.企业排口ID == port.ID)
                                .FirstOrDefault(t => t.报警异常数据类型ID == alarmType.ID);

                            if (record == null)
                            {
                                record = new 报警记录();
                                record.企业基本信息ID = port.企业基本信息ID;
                                record.企业排口ID = port.ID;
                                record.报警异常数据类型ID = alarmType.ID;
                                pCtx.报警记录.Add(record);
                            }

                            record.报警时间 = item.updatetime;
                            record.内容 = enterpriseName + "(" + port.排放口名称 + "):" +
                                        item.updatetime.ToString("yyyy-MM-dd HH:mm:ss") + "," + item.code + "定值，浓度为 " +
                                        item.rtd + ".";

                            record.报警方式 = "Email";
                            record.发送结果标志ID = 401;
                            record.是否发送 = false;
                            record.报警方式ID = 201;
                            record.发送结果 = "未发送";
                            record.次数 = 0;
                            record.管理者分级代码 = "false";
                            item.datatime = item.updatetime.AddDays(1);
                        }
                    }
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
        public static void ProcessOffline(string content)
        {
            try
            {
                var cn = Parser.GetStringByKey("CN", content);
                if (cn == null || !cn.Contains("000"))
                {
                    return;
                }

                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrWhiteSpace(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null)
                {
                    return;
                }

                var enterpriseName = CommonInformation.GetPollutionSourceNameByMn(mn);
                if (enterpriseName == null)
                {
                    return;
                }
                using (var pCtx = new PlatformXpfContext())
                {
                    var alarmType = CommonInformation.GetAlarmTypeByCode("offline");
                    if (alarmType == null)
                    {
                        return;
                    }

                    var record = pCtx.报警记录
                        .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                        .Where(t => t.企业排口ID == port.ID)
                        .FirstOrDefault(t => t.报警异常数据类型ID == alarmType.ID);
                    if (record != null)
                    {
                        record.报警时间 = datatime.Value;
                        record.是否发送 = false;
                        record.内容 = enterpriseName + "(" + port.排放口名称 + "):" +
                                    datatime.Value.ToString("yyyy-MM-dd HH:mm:ss") +
                                    "离线.";
                        pCtx.SaveChanges();
                        return;
                    }

                    record = new 报警记录
                    {
                        企业基本信息ID = port.企业基本信息ID,
                        报警时间 = datatime,
                        内容 = enterpriseName + "(" + port.排放口名称 + "):" + datatime.Value.ToString("yyyy-MM-dd HH:mm:ss") +
                             "离线.",
                        报警异常数据类型ID = alarmType.ID,
                        报警方式 = "Email",
                        发送结果标志ID = 401,
                        是否发送 = false,
                        报警方式ID = 201,
                        企业排口ID = port.ID,
                        发送结果 = "未发送",
                        次数 = 0,
                        管理者分级代码 = "false"
                    };
                    pCtx.报警记录.Add(record);
                    pCtx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
        }
        public static void ProcessOnline(string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrWhiteSpace(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null)
                {
                    return;
                }

                var enterpriseName = CommonInformation.GetPollutionSourceNameByMn(mn);
                if (enterpriseName == null)
                {
                    return;
                }
                using (var pCtx = new PlatformXpfContext())
                {

                    var alarmType = CommonInformation.GetAlarmTypeByCode("offline");
                    if (alarmType == null)
                    {
                        return;
                    }

                    var record = pCtx.报警记录
                        .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                        .Where(t => t.企业排口ID == port.ID)
                        .Where(t => t.报警异常数据类型ID == alarmType.ID).OrderByDescending(t => t.报警时间).FirstOrDefault();
                    if (record != null)
                    {
                        record.报警时间 = datatime.Value;
                        record.是否发送 = true;
                        pCtx.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
        }
    }
}
